package com.danceforyou.receipt.controller;

import com.danceforyou.common.model.view.BizData4Page;
import com.danceforyou.common.restful.exception.BizExceptionEnum;
import com.danceforyou.common.util.AssertUtil;
import com.danceforyou.common.util.Constants;
import com.danceforyou.common.util.ExcelExportUtil;
import com.danceforyou.common.util.StringUtil;
import com.danceforyou.common.vo.SqlOrderEnum;
import com.danceforyou.receipt.model.ReceiptDO;
import com.danceforyou.receipt.model.ReceiptVoucherDO;
import com.danceforyou.receipt.service.ReceiptService;
import com.danceforyou.receipt.service.ReceiptVoucherService;
import com.danceforyou.receipt.vo.ReceiptExcelVO;
import com.danceforyou.receipt.vo.ReceiptVO;
import com.danceforyou.user.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/receipt")
public class ReceiptController {

    @Autowired
    private ReceiptService receiptService;
    @Autowired
    private ReceiptVoucherService receiptVoucherService;
    @Autowired(required = false)
    private HttpSession session;

    private void dealReceiptContidion(Map<String, Object> condition) {
        for (Map.Entry<String, Object> entry : condition.entrySet()) {
            if (StringUtil.isBlank(entry.getValue().toString())) {
                condition.put(entry.getKey(), null);
            }
        }
        if (condition.get("numberType") != null) {
            switch (condition.get("numberType").toString()) {
                case "1":
                    //回款金额
                    if (condition.get("numberStart") != null) {
                        condition.put("recMoneyStart", condition.get("numberStart"));
                    }
                    if (condition.get("numberEnd") != null) {
                        condition.put("recMoneyEnd", condition.get("numberEnd"));
                    }
                    break;
                case "2":
                    //执行价
                    if (condition.get("numberStart") != null) {
                        condition.put("quotedPriceStart", condition.get("numberStart"));
                    }
                    if (condition.get("numberEnd") != null) {
                        condition.put("quotedPriceEnd", condition.get("numberEnd"));
                    }
                    break;
                case "3":
                    //成本价
                    if (condition.get("numberStart") != null) {
                        condition.put("costPriceStart", condition.get("numberStart"));
                    }
                    if (condition.get("numberEnd") != null) {
                        condition.put("costPriceEnd", condition.get("numberEnd"));
                    }
                    break;
                default: break;
            }
        }
        if (condition.get("dateType") != null) {
            switch (condition.get("dateType").toString()) {
                case "1":
                    //创建日期
                    if (condition.get("dateStart") != null) {
                        condition.put("createDateStart", condition.get("dateStart"));
                    }
                    if (condition.get("dateEnd") != null) {
                        condition.put("createDateEnd", condition.get("dateEnd"));
                    }
                    break;
                case "2":
                    //审核日期
                    if (condition.get("dateStart") != null) {
                        condition.put("auditDateStart", condition.get("dateStart"));
                    }
                    if (condition.get("dateEnd") != null) {
                        condition.put("auditDateEnd", condition.get("dateEnd"));
                    }
                    break;
                case "3":
                    //回款日期
                    if (condition.get("dateStart") != null) {
                        condition.put("recDateStart", condition.get("dateStart"));
                    }
                    if (condition.get("dateEnd") != null) {
                        condition.put("recDateEnd", condition.get("dateEnd"));
                    }
                    break;
                case "4":
                    //投放日期
                    if (condition.get("dateStart") != null) {
                        condition.put("putDateStart", condition.get("dateStart"));
                    }
                    if (condition.get("dateEnd") != null) {
                        condition.put("putDateEnd", condition.get("dateEnd"));
                    }
                    break;
                default: break;
            }
        }
        if (condition.get("putAddress") != null && condition.get("putAddress").toString().equals("全部")) {
            condition.remove("putAddress");
        }
        if (condition.get("status") != null && condition.get("status").toString().equals("ALL")) {
            condition.remove("status");
        }
    }

    /**
     * 根据排期ID获取回款记录
     * @param orderId 排期ID
     * @return List<ReceiptVO>
     */
    @RequestMapping(value = "/listReceiptByOrderId", method = RequestMethod.GET)
    public List<ReceiptVO> listReceiptByOrderId(Long orderId) {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        AssertUtil.notNull(loginUser, BizExceptionEnum.AUTHFAILURE);
        return receiptService.queryList(new HashMap<String, Object>(){{
            put("orderId", orderId);
            put("isDelete", false);
        }});
    }

    /**
     * 分页查询我的回款记录
     * @param bizData4Page BizData4Page
     * @return BizData4Page
     */
    @RequestMapping(value = "/querySelfReceiptPage", method = RequestMethod.GET)
    public BizData4Page<ReceiptVO> querySelfReceiptPage(BizData4Page<ReceiptVO> bizData4Page) {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        AssertUtil.notNull(loginUser, BizExceptionEnum.AUTHFAILURE);
        Map<String, Object> condition = bizData4Page.getCondition();
        dealReceiptContidion(condition);
        condition.put("createUserId", loginUser.getId());
        condition.put("isDelete", false);
        bizData4Page.setStat(true);
        receiptService.queryPageByDataPerm(bizData4Page);
        return bizData4Page;
    }

    /**
     * 分页查询待审核回款记录
     * @param bizData4Page BizData4Page
     * @return BizData4Page
     */
    @RequestMapping(value = "/queryAuditReceiptPage", method = RequestMethod.GET)
    public BizData4Page<ReceiptVO> queryAuditReceiptPage(BizData4Page<ReceiptVO> bizData4Page) {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        AssertUtil.notNull(loginUser, BizExceptionEnum.AUTHFAILURE);
        Map<String, Object> condition = bizData4Page.getCondition();
        dealReceiptContidion(condition);
        condition.putIfAbsent("status", Constants.RECEIPT_STATUS_FILLIN);
        condition.put("isDelete", false);
        bizData4Page.setStat(true);
        receiptService.queryPageByDataPerm(bizData4Page);
        return bizData4Page;
    }

    /**
     * 分页查询统计回款记录
     * @param bizData4Page BizData4Page
     * @return BizData4Page
     */
    @RequestMapping(value = "/queryStatReceiptPage", method = RequestMethod.GET)
    public BizData4Page<ReceiptVO> queryStatReceiptPage(BizData4Page<ReceiptVO> bizData4Page) {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        AssertUtil.notNull(loginUser, BizExceptionEnum.AUTHFAILURE);
        Map<String, Object> condition = bizData4Page.getCondition();
        dealReceiptContidion(condition);
        condition.put("isDelete", false);
        if (loginUser.getRole().getRoleType().equals(Constants.ROLE_MJB_CODE)) {
            condition.putIfAbsent("mediumUserId", loginUser.getId());
        }
        if (loginUser.getRole().getRoleType().equals(Constants.ROLE_XSB_CODE)) {
            condition.putIfAbsent("orderUserId", loginUser.getId());
        }
        bizData4Page.setStat(true);
        receiptService.queryPageByDataPerm(bizData4Page);
        return bizData4Page;
    }

    /**
     * 新建回款
     * @param Receipt 回款信息
     * @return boolean
     */
    @RequestMapping(value = "/saveReceiptInfo", method = RequestMethod.POST)
    public boolean saveReceiptInfo(ReceiptDO Receipt) {
        receiptService.saveInfo(Receipt);
        return true;
    }

    /**
     * 修改回款
     * @param Receipt 回款信息
     * @return boolean
     */
    @RequestMapping(value = "/updateReceiptInfo", method = RequestMethod.POST)
    public boolean updateReceiptInfo(ReceiptDO Receipt) {
        receiptService.updateInfo(Receipt);
        return true;
    }

    /**
     * 删除回款
     * @param ids 回款IDS
     * @return int
     */
    @RequestMapping(value = "/deleteReceiptInfoByIds", method = RequestMethod.POST)
    public int deleteInfoByIds(String ids) {
        return receiptService.deleteInfoByIds(ids);
    }

    /**
     * 审核通过回款申请
     * @param fileList 回款凭证
     * @param ids 回款IDS
     * @return int
     */
    @RequestMapping(value = "/setReceiptAuditPass", method = RequestMethod.POST)
    public int setReceiptAuditPass(@RequestParam MultipartFile[] fileList, String ids) {
        return receiptService.setReceiptAuditPass(fileList, ids);
    }

    /**
     * 审核不通过回款申请
     * @param ids 回款IDS
     * @param auditDesc 审核意见
     * @return int
     */
    @RequestMapping(value = "/setReceiptAuditNoPass", method = RequestMethod.POST)
    public int setReceiptAuditNoPass(String ids, String auditDesc) {
        return receiptService.setReceiptAuditNoPass(ids, auditDesc);
    }

    /**
     * 获取回款记录凭证列表
     * @param receiptId 回款ID
     * @return List<ReceiptVoucherDO>
     */
    @RequestMapping(value = "/listReceiptVoucherByReceiptId", method = RequestMethod.GET)
    public List<ReceiptVoucherDO> listReceiptVoucherByReceiptId(Long receiptId) {
        return receiptVoucherService.listByProperty("receiptId", receiptId);
    }

    /**
     * 分页查询统计回款记录
     * @param condition 查询条件
     */
    @RequestMapping(value = "/exportStatReceipt", method = RequestMethod.GET)
    public void exportStatReceipt(@RequestParam Map<String, Object> condition, HttpServletResponse response) {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        AssertUtil.notNull(loginUser, BizExceptionEnum.AUTHFAILURE);
        dealReceiptContidion(condition);
        condition.put("isDelete", false);
        if (loginUser.getRole().getRoleType().equals(Constants.ROLE_MJB_CODE)) {
            condition.putIfAbsent("mediumUserId", loginUser.getId());
        }
        if (loginUser.getRole().getRoleType().equals(Constants.ROLE_XSB_CODE)) {
            condition.putIfAbsent("orderUserId", loginUser.getId());
        }
        List<ReceiptVO> ReceiptList = receiptService.queryList(condition, condition.get("orderBy").toString(), condition.get("sortBy").toString().equals("ASC") ? SqlOrderEnum.ASC : SqlOrderEnum.DESC);
        List<Object> excelVOList = new ArrayList<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (ReceiptVO receipt : ReceiptList) {
            ReceiptExcelVO excelVO = new ReceiptExcelVO();
            excelVO.setId(receipt.getId());
            excelVO.setOrderId(receipt.getOrderId());
            excelVO.setCustomerBrand(receipt.getCustomerBrand());
            excelVO.setMediumName(receipt.getMediumName());
            excelVO.setMediumType(receipt.getMediumType() == 1 ? "公众号" : "视频号");
            excelVO.setPutDate(dateFormat.format(receipt.getPutDate()));
            excelVO.setPutAddress(receipt.getPutAddress());
            excelVO.setQuotedPrice(receipt.getQuotedPrice());
            excelVO.setCostPrice(receipt.getCostPrice());
            excelVO.setProfit(receipt.getProfit());
            excelVO.setProfitRate(receipt.getProfitRate());
            excelVO.setRecMoney(receipt.getRecMoney());
            excelVO.setRecDate(dateFormat.format(receipt.getRecDate()));
            excelVO.setCreateUserName(receipt.getCreateUserName());
            excelVO.setCreateDate(dateTimeFormat.format(receipt.getCreateDate()));
            excelVO.setCreateDesc(receipt.getCreateDesc());
            excelVO.setAuditUserName(receipt.getAuditUserName());
            excelVO.setAuditDate(dateTimeFormat.format(receipt.getAuditDate()));
            excelVO.setMediumUserName(receipt.getMediumUserName());
            excelVO.setOrderUserName(receipt.getOrderUserName());
            switch (receipt.getStatus()) {
                case Constants.RECEIPT_STATUS_FILLIN: excelVO.setStatus("待审核"); break;
                case Constants.RECEIPT_STATUS_NOPASS: excelVO.setStatus("审核不通过"); break;
                case Constants.RECEIPT_STATUS_PASSED: excelVO.setStatus("审核通过"); break;
            }
            excelVOList.add(excelVO);
        }
        String[] fieldTitle = {"回款编号", "排期编号", "客户品牌", "媒体名称", "媒体类型", "投放日期", "投放位置", "执行价", "成本价", "利润",
                "利润率", "回款金额", "回款日期", "申请人", "申请时间", "申请事由", "审核人", "审核时间", "对接媒介", "对接销售",
                "状态"};
        int[] fieldWidth = {10, 10, 20, 20, 10, 10, 10, 10, 10, 10,
                10, 10, 20, 10, 20, 40, 10, 20, 10, 10,
                10};
        ExcelExportUtil.export("回款记录列表", fieldTitle, fieldWidth, excelVOList, response);
    }
}
